package com.symaster.gameengine.test;

import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;

import java.nio.*;

import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;

public class Main {

    private long window;

    public void run() {
        System.out.println("LWJGL version: " + Version.getVersion());
        init();
        loop();
        glfwFreeCallbacks(window);
        glfwDestroyWindow(window);
        glfwTerminate();
        glfwSetErrorCallback(null).free();
    }

    private void init() {
        GLFWErrorCallback.createPrint(System.err).set();
        if (!glfwInit()) {
            throw new IllegalStateException("Unable to initialize GLFW");
        }

        // 配置 GLFW
        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);

        // 创建窗口
        window = glfwCreateWindow(800, 600, "Hello LWJGL", NULL, NULL);
        if (window == NULL) {
            throw new RuntimeException("Failed to create the GLFW window");
        }

        // 设置窗口的上下文为当前线程
        glfwMakeContextCurrent(window);
        glfwSwapInterval(1); // 启用 V-Sync
        glfwShowWindow(window);

        GL.createCapabilities(); // 初始化 OpenGL 上下文
    }

    private void loop() {
        // 设置清屏颜色
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        while (!glfwWindowShouldClose(window)) {
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 清除屏幕

            // 绘制三角形
            glBegin(GL_TRIANGLES);
            glColor3f(1.0f, 0.0f, 0.0f); // 顶点1 (红色)
            glVertex2f(-0.5f, -0.5f);

            glColor3f(0.0f, 1.0f, 0.0f); // 顶点2 (绿色)
            glVertex2f(0.5f, -0.5f);

            glColor3f(0.0f, 0.0f, 1.0f); // 顶点3 (蓝色)
            glVertex2f(0.0f, 0.5f);
            glEnd();

            glfwSwapBuffers(window); // 交换颜色缓冲区
            glfwPollEvents(); // 轮询事件
        }
    }

    public static void main(String[] args) {
        new Main().run();
    }
}
